package com.baor.controller;

import com.baor.domain.StuVo;
import com.baor.service.UploadService;
import com.baor.utils.AjaxResult;
import com.baor.utils.ExcelUtils;
import com.baor.utils.Upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping(value = "/file")
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @RequestMapping("upload")
    public AjaxResult<?> upload(MultipartFile[] files){
        return AjaxResult.success(new Upload().uploads(files, "files/images/"));
    }

    @RequestMapping("excel")
    public String importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        String name = file.getOriginalFilename();
        if(name.length() < 5 || !name.substring(name.length() - 5).equals(".xlsx")) {
            throw new Exception("文件格式错误");
        }
        //获取Excel中的数据
        List<StuVo> detaileds = ExcelUtils.excelToShopIdList(file.getInputStream());
        System.out.println(detaileds.get(0));
        //遍历添加数据库
        for (int i = 0; i < detaileds.size(); i++) {
            StuVo detailed = detaileds.get(i);
            uploadService.addDetailed(detailed);
        }
        //return返回的是我之前的项目页面，你可以自行修改
        return "redirect:/show";
    }

}
